# apps/menus/models.py
from django.db import models

from apps.tenants.models import Tenant
from apps.users.models import QBUser

class Menu(models.Model):
    """
    菜单/权限项
    支持无限层级，可用于左侧菜单、按钮权限等
    """
    TYPE_CHOICES = (
        ('menu', '菜单'),
        ('button', '按钮'),
    )

    title = models.CharField(max_length=50, verbose_name="标题")
    name = models.CharField(max_length=50, unique=True, verbose_name="唯一标识（前端路由名）")
    path = models.CharField(max_length=100, blank=True, verbose_name="路由路径")
    component = models.CharField(max_length=100, blank=True, verbose_name="组件路径")
    icon = models.CharField(max_length=50, blank=True, verbose_name="图标（Element Plus 图标名）")
    menu_type = models.CharField(max_length=10, choices=TYPE_CHOICES, default='menu', verbose_name="类型")
    parent = models.ForeignKey('self', null=True, blank=True, on_delete=models.CASCADE, related_name='children', verbose_name="父级菜单")
    roles = models.ManyToManyField(QBUser, related_name='menus', blank=True, verbose_name="可见角色")
    order = models.PositiveIntegerField(default=0, verbose_name="排序")
    is_active = models.BooleanField(default=True, verbose_name="是否启用")
    is_external = models.BooleanField(default=False, verbose_name="是否外链")

    tenant = models.ForeignKey(Tenant, on_delete=models.CASCADE, null=True, db_index=True, verbose_name="租户")

    class Meta:
        db_table = 'qb_menus'
        verbose_name = '菜单管理'
        verbose_name_plural = '菜单管理'
        ordering = ['order']
        indexes = [
            models.Index(fields=['tenant'], name='idx_menu_tenant'),
            models.Index(fields=['parent'], name='idx_menu_parent'),
        ]

    def __str__(self):
        return self.title

    def get_ancestors(self):
        """获取所有父级（用于面包屑）"""
        ancestors = []
        parent = self.parent
        while parent:
            ancestors.append(parent)
            parent = parent.parent
        return ancestors[::-1]